import {Component, ViewChild} from '@angular/core';
import {AlertController, Content, IonicPage, ModalController, NavParams, ViewController} from 'ionic-angular';
import {DialogProvider} from "@providers/dialog";
import {WorkerProvider} from "@providers/interface/worker";
import {Observable} from "rxjs/Observable";
import {Util} from "@providers/util";
import {StorageProvider} from "@providers/storage";

@IonicPage()
@Component({
  selector: 'page-worker-materiel-store',
  templateUrl: 'worker-materiel-store.html',
})
export class WorkerMaterielStorePage {

  userInfo = this.storage.read("userInfo");

  @ViewChild(Content) content: Content;
  categorys: any[] = [];//辅材分类
  allPros: any[] = [];//所有的辅材
  currentPros: any[] = [];//当前分类的辅材
  choosePros: any[] = [];//选中的辅材
  sum: number = 0;//选中辅材的总价
  num: number = 0;//选中辅材的个数
  isClick: boolean = false;//Popover是否显示
  QUANTITY: number;

  name: any;
  phone: number;
  safe: any;
  address: any;
  number: number;
  BJ: any;

  apply_info: any = {
    product_id: 0,
    product_sum: 0,
    SERVICETYPEID: 0,
    partyid: this.userInfo['PARTYID']
  };

  diyCosts: any = [];//自定义费用
  fixedCosts: any = [];//固定费用

  LLBJ:any=this.navParams.data; //领料标记

  constructor(private navParams: NavParams,
              private worker: WorkerProvider,
              private dialog: DialogProvider,
              private alertCrtl: AlertController,
              private storage: StorageProvider,
              private viewCtrl: ViewController,
              private modalCtrl: ModalController) {
  }

  updata() {
    this.sum = 0;
    this.num = 0;
    this.currentPros.forEach(value => {
      if(Util.isNull(value.PRICE)||value.PRICE=='')value.PRICE=0;
    });
    this.choosePros.forEach(value => {
      if(Util.isNull(value.PRICE)||value.PRICE=='')value.PRICE=0;
      this.sum = +(this.sum + +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
      this.num = +(this.num + +value.QUANTITY).toFixed(2);
    });
  }

  ionViewDidLoad() {
    if (Util.isNull(this.navParams.data.ID)) {
      this.BJ = 0;
    } else {
      this.BJ = 1;
    }
    this.number = this.navParams.data.ID;
    let GUARANTEE=this.navParams.data.GUARANTEE;
    if(GUARANTEE=='保内'){
      this.safe = 0;
    }else if(GUARANTEE=='保外'){
      this.safe = 1;
    }else if(GUARANTEE=='延保'){
      this.safe = 2;
    }
    this.name = this.navParams.data.NAME;
    this.phone = this.navParams.data.MOBILE;
    this.address = this.navParams.data.ADDRESS;
    console.info(this.navParams);

    this.queryCategory().subscribe(message => {
      console.info(message);
      this.categorys = message.data;
      //初始化分类的选中辅材个数
      this.categorys.forEach((value, index) => {
        if (index == 0 || value.num > 0) {
          this.queryPro(value, index);
        } else {
          this.queryPro2(value, index);
        }
      });
    }, error => {
      this.dialog.showAlert("请检查网络");
    });
  }

  dismiss(data?: any) {
    if (data) {
      this.viewCtrl.dismiss(data);
      return;
    }
    this.viewCtrl.dismiss();
  }

  /**
   * 确定按钮点击事件
   */
  onSubmit() {
    this.fixedCosts = this.fixedCosts.filter(value => {
      return value.QUANTITY > 0;
    });
    this.diyCosts = this.diyCosts.filter(value => {
      return value.QUANTITY > 0;
    });
    this.choosePros = this.choosePros.filter(value => {
      return value.QUANTITY > 0;
    });
    if(Util.isNull(this.diyCosts.concat(this.fixedCosts.concat(this.choosePros)))){
      return this.dialog.showAlert("请选择物料");
    }
    this.worker.insertParts({
      "LLBJ":this.LLBJ,
      "NAME": this.name,
      "PHONE": this.phone,
      "ADDRESS": this.address,
      "BXLX": this.safe,
      "GDID": this.number,
      "fixedCosts": this.fixedCosts,
      "diyCosts": this.diyCosts,
      "materialCosts": this.choosePros,
      "SUM": this.sum,
      "partyId": this.userInfo['PARTYID']
    }).then(v => {
      this.dialog.showAlert('领料申请成功');
      this.dismiss();
    }).catch(e => {
    });
  }

  /**
   * 清空选中的辅材
   */
  clearAll() {
    this.dialog.showConfirm(() => {
      this.choosePros.forEach(value => {
        value.QUANTITY = 0;
      });
      this.calculateChoose();
    }, "是否清空所有已选中的辅材！");
  }

  /**
   * 辅材数量改变点击事件
   * @param pro 选中的商品
   * @param index 为0时表示减小，为1时表示增加
   */
  quantityChange(pro: any, index?: number) {
    switch (index) {
      case 0:
        if (pro.QUANTITY == 0) return;
        pro.QUANTITY = +(pro.QUANTITY - 1).toFixed(2);
        if (pro.QUANTITY < 0) {
          pro.QUANTITY = 0;
        }
        break;
      case 1:
        pro.QUANTITY = +(+pro.QUANTITY + 1).toFixed(2);
        break;
    }
    this.calculateChoose();
  }

  //失去焦点改变辅材数量
  eqc(pro: any) {
    this.editChange(pro);
  }

  //点击enter改变辅材数量
  kdqc(event, pro: any) {
    if (event.keyCode == 13) {
      this.editChange(pro);
    }
  }

  editChange(pro: any) {
    this.allPros.forEach(val => {
      val.forEach(value => {
        if (value.ZJ == pro.ZJ) {
          if (pro.QUANTITY == null) {
            value.QUANTITY = 0;
            pro.QUANTITY = 0;
          } else {
            pro.QUANTITY = +pro.QUANTITY.toFixed(2);
            if (pro.QUANTITY < 0) {
              pro.QUANTITY = 0;
            }
            value.QUANTITY = pro.QUANTITY;
          }
        }
      });
    });
    this.calculateChoose();
  }

  /**
   * 格式化选中的辅材，并计算个数和总费用
   */
  calculateChoose() {
    //获取所有的数量不为0的辅材
    let temp = [];
    this.allPros.forEach(value => {
      value.forEach(val => {
        temp.push(val);
      })
    });
    this.choosePros = temp.filter(value => {
      return value.QUANTITY > 0;

    });
    //计算数量不为0的辅材的个数和总价
    this.sum = 0;
    this.num = 0;
    this.choosePros.forEach(value => {

      this.sum = +(this.sum + +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
      this.num = +(this.num + +value.QUANTITY).toFixed(2);
    });
    if (this.num == 0) {
      this.isClick = false;
    }
    //计算左侧的分类右上角的数字
    this.categorys.forEach(value => {
      value.num = 0;
      this.choosePros.forEach(val => {
        if (value.PRODUCT_CATEGORY_ID == val.PRODUCT_CATEGORY_ID) {
          value.num = +(+value.num + +val.QUANTITY).toFixed(2);
        }
      });
    });
  }

  /**
   * 根据分类查找出所有的辅材
   * @param category 分类
   * @param index 序号
   */
  queryPro(category: any, index: number) {
    if (this.allPros[index]) {
      this.categorys.forEach(value => {
        value["isSelected"] = false;
      });
      category.isSelected = true;
      this.currentPros = this.allPros[index];
      for(let i = 0; i<this.currentPros.length;i++){
        this.currentPros[i]['oldPic'] = this.currentPros[i].PRICE;
      }
      return;
    }

    this.worker.getFCFLSPFC({
      "FLID": category.PRODUCT_CATEGORY_ID,
      'SPID': "",

      //'SPID': this.product_id
    }).then(v => {
      this.allPros[index] = v.data;
      //初始化辅材数量
      console.info(this.allPros[index]);
      this.allPros[index].forEach(value => {
        value.QUANTITY = 0;
        console.info(value);
      });
      this.categorys.forEach(value => {
        value["isSelected"] = false;
      });
      category.isSelected = true;
      this.currentPros = this.allPros[index];
      for(let i = 0; i<this.currentPros.length;i++){
        this.currentPros[i]['oldPic'] = this.currentPros[i].PRICE;
      }
      this.calculateChoose();
    }).catch(e => {
      this.dialog.showAlert("请检查网络");
    });
  }

  /**
   * 查找出所有的辅材用辅材分类分组
   * @param category 分类
   * @param index 序号
   */
  queryPro2(category: any, index: number) {
    this.worker.getFCFLSPFC({
      "FLID": category.PRODUCT_CATEGORY_ID,
      'SPID': this.apply_info.product_id,

      //'SPID': this.product_id
    }).then(v => {
      this.allPros[index] = v.data;
      //初始化辅材数量
      console.info(this.allPros[index]);
      this.allPros[index].forEach(value => {
        value.QUANTITY = 0;
      });
      this.calculateChoose();
    }).catch(e => {
      this.dialog.showAlert("请检查网络");
    });
  }

  /**
   * 查询辅材分类
   */
  queryCategory(level: number = 1, category_type: string = 'terrace'): Observable<any> {
    return Observable.create((observer) => {
      this.worker.getFCFL({
        'SPID': this.apply_info.product_id,
        'SERVICETYPEID': this.apply_info.SERVICETYPEID
      }).then(v => {
        observer.next(v);
        observer.complete();
      }).catch(e => {
        observer.error(e);
      });
    });
  }

  /**
   * 创建modal
   * @param page
   * @param data
   */
  showQueryMaterialModal() {
    let modal = this.modalCtrl.create('MqueryMaterialPage',
      {
        'allPros': this.allPros,
        'categorys': this.categorys,
        'choosePros': this.choosePros
      });
    modal.onDidDismiss(data => {
      if (data) {
        this.calculateChoose();
      }
    });
    modal.present();
  }

  setPrice(item) {
    let alert = this.alertCrtl.create({
      message: "输入价格",
      inputs: [{type: 'number', name: 'price'}],
      buttons: [{
        text: "取消", handler: () => {
        }
      }, {
        text: "确定", handler: (res) => {
          if (item.oldPic>res.price){
            return this.dialog.showAlert("收费价格低于限价， 请调整价格。")
          }
          item.PRICE = res.price;
          this.updata()
        }
      }]
    });
    alert.present();
  }
}
